package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBException;

import shared.Cal;
import shared.Task;
import shared.User;

public class SimpleTcpClient {
    private static String command = "PUT";
    private static User user = new User("John Doe", "mygirlfriendsname");
    private static Task newTask = new Task("not-executed", "17-09-2012", "Awesome event", "tch-1337",
			"John Doe, hilde", "It's gonna be awesome maaan");

    public static void main(String args[])  {
        try {
            // IP address of the server,
            InetAddress serverAddress = InetAddress.getByName("localhost");
            
            // It is the same port where server will be listening.
            int serverPort = 7896;
            // Open a socket for communication.
            Socket socket = new Socket(serverAddress, serverPort);
            
            // Get data output stream to send a String command to server.
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF(command);            
            dataOutputStream.flush();
            
            // Now switch to listening mode for receiving message from server.
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            String response = dataInputStream.readUTF();
            System.out.println("Message from Server: " + response);        
            
            Cal sendData = new Cal();
            sendData.users.add(user);
            System.out.println("sendData created");
            
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.writeUTF(Cal.serialize(sendData));
            System.out.println("data send");
            
            // Finnaly close the socket. 
            socket.close();
            
        } catch (IOException ex) {
            Logger.getLogger(SimpleTcpClient.class.getName()).log(Level.SEVERE, null, ex);
            
            System.out.println("error message: " + ex.getMessage());
        } catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
    }
}